import React, { createContext, useContext, useState, useCallback, useMemo, ReactNode } from 'react';
import { ExperimentDataSeries, ExperimentDataCategory } from '../types';

export type ChartType = 'line' | 'bar' | 'scatter' | 'area' | 'stacked' | 'stacked-line' | 'stacked-area' | 'stepped-line' | 'pie' | 'doughnut' | 'radar';

export interface VisualizationItem {
  id: string; // 唯一ID: experimentId-categoryId-seriesId
  experimentId: number;
  experimentName?: string;
  categoryId: number;
  categoryName: string;
  seriesId: number;
  seriesName: string;
  seriesUnit?: string;
  dataLength: number; // 数据长度
  chartType: ChartType;
}

interface VisualizationContextType {
  visualizationItems: VisualizationItem[];
  addVisualizationItem: (
    experimentId: number,
    experimentName: string | undefined,
    category: ExperimentDataCategory,
    series: ExperimentDataSeries
  ) => void;
  removeVisualizationItem: (id: string) => void;
  updateChartType: (id: string, chartType: ChartType) => void;
  clearAll: () => void;
  isItemVisualized: (experimentId: number, seriesId: number) => boolean;
  getVisualizationItemId: (experimentId: number, categoryId: number, seriesId: number) => string;
}

const VisualizationContext = createContext<VisualizationContextType | undefined>(undefined);

export const VisualizationProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [visualizationItems, setVisualizationItems] = useState<VisualizationItem[]>([]);

  const generateId = useCallback((experimentId: number, categoryId: number, seriesId: number) => {
    return `${experimentId}-${categoryId}-${seriesId}`;
  }, []);

  const addVisualizationItem = useCallback((
    experimentId: number,
    experimentName: string | undefined,
    category: ExperimentDataCategory,
    series: ExperimentDataSeries
  ) => {
    const id = generateId(experimentId, category.id, series.id);
    
    setVisualizationItems(prev => {
      // 检查是否已存在
      if (prev.some(item => item.id === id)) {
        return prev;
      }

      const newItem: VisualizationItem = {
        id,
        experimentId,
        experimentName,
        categoryId: category.id,
        categoryName: category.name,
        seriesId: series.id,
        seriesName: series.name,
        seriesUnit: series.unit,
        dataLength: series.data_length, // 存储数据长度
        chartType: 'line', // 默认折线图
      };

      return [...prev, newItem];
    });
  }, [generateId]);

  const removeVisualizationItem = useCallback((id: string) => {
    setVisualizationItems(prev => prev.filter(item => item.id !== id));
  }, []);

  const updateChartType = useCallback((id: string, chartType: ChartType) => {
    setVisualizationItems(prev =>
      prev.map(item => (item.id === id ? { ...item, chartType } : item))
    );
  }, []);

  const clearAll = useCallback(() => {
    setVisualizationItems([]);
  }, []);

  const isItemVisualized = useCallback((experimentId: number, seriesId: number) => {
    return visualizationItems.some(
      item => item.experimentId === experimentId && item.seriesId === seriesId
    );
  }, [visualizationItems]);

  const getVisualizationItemId = useCallback((experimentId: number, categoryId: number, seriesId: number) => {
    return generateId(experimentId, categoryId, seriesId);
  }, [generateId]);

  const contextValue = useMemo(() => ({
    visualizationItems,
    addVisualizationItem,
    removeVisualizationItem,
    updateChartType,
    clearAll,
    isItemVisualized,
    getVisualizationItemId,
  }), [visualizationItems, addVisualizationItem, removeVisualizationItem, updateChartType, clearAll, isItemVisualized, getVisualizationItemId]);

  return (
    <VisualizationContext.Provider value={contextValue}>
      {children}
    </VisualizationContext.Provider>
  );
};

export const useVisualization = () => {
  const context = useContext(VisualizationContext);
  if (context === undefined) {
    throw new Error('useVisualization must be used within a VisualizationProvider');
  }
  return context;
};

